import _ from 'lodash'
import { constantRoutes } from '@/router'
import { routerMenu } from '@/api/system/auth/menu'
import Layout from '@/layout'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }) {
    return routerMenu().then(response => {
      const accessedRoutes = generateRouter(response.data)
      commit('SET_ROUTES', accessedRoutes)
      return accessedRoutes
    })
  }
}

function generateRouter(list, route_path = null, isChildren = false) {
  const routers = []

  _.forEach(list, item => {
    if (item.status === 0) return true

    const router = {
      name: `views_${item.menu_id}`,
      path: item.route_path,
      meta: { title: item.menu_name, affix: item.affix === 1, hidden: item.hidden === 1 }
    }

    // 构造路径  父级路径是null  返回当前路径  否则判断父级路径不等于 / 返回父级路径拼接当前路径 否则只返回当前路径
    const path = route_path === null ? item.route_path : `${route_path !== '/' ? route_path : ''}/${item.route_path}`

    console.log('path', `@/views${path}`, item.menu_type === 1 ? '目录' : '页面')

    // 是个目录
    if (item.menu_type === 1) {
      if (/\/\/$/.test(path)) return true

      if (isChildren) {
        try {
          require.resolve(`@/views${path}`)
          router.component = require(`@/views${path}`).default
        } catch (e) {
          return true
        }
      } else {
        router.component = Layout
      }

      if (_.get(item, 'redirect', '') !== '') {
        router.redirect = item.redirect
      }

      if (_.get(item.children, 'length', 0) > 0) {
        router.children = generateRouter(item.children, path, true)

        // children 为 0，则不显示
        if (_.get(router.children, 'length', 0) === 0) {
          return true
        }
      }
    } else if (item.menu_type === 2) {
      try {
        require.resolve(`@/views${path}`)
        router.component = require(`@/views${path}`).default
      } catch (e) {
        return true
      }
    }

    if (router === null) return true

    if (item.icon_name) {
      router.meta.icon = item.icon_name
    }

    routers.push(router)
  })

  if (!isChildren) {
    routers.push({
      path: '*',
      redirect: '/404',
      hidden: true
    })
  }

  return routers
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
